'use strict'
let openid=''
class treelist{

  constructor (mdb) {
    this.mdb = mdb || null
  }
  async delete(c){
    let data=JSON.parse(c)
    this.mdb.connect().then(client=>{
      client.query('delete from users where uid=$1',[data.uid]).then(res=>{  
      }).then(res=>{
        client
      })
    })

  }
  async get (c) {
    let login_url=`https://api.weixin.qq.com/sns/jscode2session`
        +`?appid=${c.service.wxkey.appid}`
        +`&secret=${c.service.wxkey.secret}`
        +`&js_code=${c.query.code}`
        +`&grant_type=authorization_code`
        let result=await gohttp.get(login_url)
        let r=result.json()
        openid=r.openid
        if(r.openid===undefined){
            c.status(500)
            return
        }

        let info={
            openid:r.openid,
            expires:7200000,
            timestamp:Date.now(),
            random:Math.random()
        }
        
        let token=c.helper.aesEncrypt(JSON.stringify(info),c.service.tokenKey)
        return token
  }
  async insert(c){
    let data=JSON.parse(c)    
    //let userid=data.uid;
    //如果uid=0或者时users表中没有对应的uid
    let sql1=`select from users where uid=${data.uid}`
    let r1=await this.mdb.query(sql1)
    let result1=r1['rows'];
    console.log('这是result1的值',result1)
    if(!data.uimg || !data.uname){
      console.log('没有用户名或者用户头像')
      return 'fail'
    }else if(data.uid==0 || Number(result1)==0){
      console.log('开始插入数据')
      let sql='select * from users';
      let r=await this.mdb.query(sql);
     
      let uid=r['rows'].length+1; 
      this.mdb.connect().then(client=>{
        client.query('insert into users values($1::int,$2::varchar(255),$2::varchar(20),$3::int,$4::int,$5::text,$6::text,$7::text,$8::text)',[uid,openid,data.uname,uid,0,'','','',data.uimg]).then(res=>{
                    
        })
      })
      console.log('返回的uid数据是：',uid)
      return {'uid':uid}
    }else{
      console.log('不能重复登陆')
      return 'fail'
    }
  }
 
}

module.exports = treelist
